package com.joven.shelltest.service.impl;

import com.joven.shelltest.model.JovenEvent;
import com.joven.shelltest.model.Mail;
import com.joven.shelltest.service.JovenService;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @Author wzj
 * @Date 2023-08-10 15:01
 **/
@Service
public class JovenServiceImpl implements JovenService {

    @Autowired
    ApplicationContext context;

    @Override
    public void sendMail(Mail mail) {
        System.err.println("----开始执行的监听事务");
        this.context.publishEvent(new JovenEvent(this, mail));
        System.err.println("----监听事务执行完成了");
    }

    @TimeLimiter(name = "slowOperationTimeLimiter", fallbackMethod = "fallback")
    @Override
    public CompletableFuture<String> testSlow() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);// 模拟耗时操作
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "Slow operation completed";
        });
    }

    public CompletableFuture<String> fallback(Throwable t) {
        System.out.println("Fallback method called due to timeout：" + t);
        return CompletableFuture.completedFuture("serviceImpl timed out, please try again later.");
    }
}
